layui.define(['form', 'zadmin', 'layer'], function(exports) {
    var form = layui.form,
        $ = layui.jquery,
        zadmin = layui.zadmin,
        layer = layui.layer,
        mods = {},
        selects = {},
        options = {},
        new_id = 1,
        types = {
            text: '文本框',
            textarea: '多行文本框',
            number: '数字',
            password: '密码',
            switch: '开关',
            date: '日期',
            radio: '单选框',
            checkbox: '复选框',
            select: '下拉框',
            multiselect: '多选下拉框',
        };

    var loading = zadmin.loading();

    function makeItem(item = {}) {
        var defaultItem = {
            'title': '新资料项',
            'defaultvalue': '',
            'type': 'text',
            'setting': '',
            'tips': '',
            'available': 1,
            'required': 0,
            'mods': ''
        };
        if (!item.field_id) {
            item.field_id = 'new_'+new_id;
            new_id++;
        }
        for (var x in defaultItem) {
            if (typeof item[x] == 'undefined' || item[x] == null) {
                item[x] = defaultItem[x];
            }
        }

        var code = '<tr>';
        code += '<td>';
        if(typeof item.field_id=='string' && item.field_id.substr(0,3)=='new'){
            code += '<button class="layui-btn layui-btn-sm" data-op="delete" type="button">删除</button>';
        }else{
            code += '<input type="checkbox" name="delete[]" value="' + item.field_id + '" lay-skin="primary">';
        }
        code += '<input type="hidden" name="field_id[]" value="' + item.field_id + '"><input type="hidden" name="setting[]" value="' + item.setting + '">';
        code += '</td>';
        code += '<td><input type="text" name="title[]" required lay-verify="required" placeholder="不超过16个字" autocomplete="off" class="layui-input" value="' + item.title + '" maxlength="16"></td>';
        code += '<td><select name="type[]">';
        for (var x in types) {
            code += '<option value="' + x + '"' + (x == item.type ? ' selected="selected"' : '') + '>' + types[x] + '</option>';
        }
        code += '</td>';
        code += '<td><input type="hidden" name="defaultvalue[]" value="' + item.defaultvalue + '"><span id="defaultvalue_' + item.field_id + '">' + item.defaultvalue + '</span></td>';
        code += '<td><input type="checkbox" lay-skin="switch" name="available[]" value="1" ' + (item.available == 1 ? ' checked=""' : '') + '></td>';
        code += '<td><input type="checkbox" lay-skin="switch" name="required[]" value="1" ' + (item.required == 1 ? ' checked=""' : '') + '></td>';
        code += '<td><div id="xm_' + item.field_id + '"></div></td>';
        code += '<td><input type="text" name="tips[]" autocomplete="off" class="layui-input" value="' + item.tips + '"></td>';
        code += '<td>';
        code += '<div class="layui-btn-group"><button type="button" class="layui-btn layui-btn-sm" data-op="up"><i class="layui-icon layui-icon-up"></i></button><button type="button" class="layui-btn layui-btn-sm" data-op="down"><i class="layui-icon layui-icon-down" ></i></button><button type="button" class="layui-btn layui-btn-sm" data-op="set"><i class="layui-icon layui-icon-set" ></i></button></div></td>';

        code += '</tr>';
        $('#datalist').append(code);
        options[item.field_id] = {
            el: '#xm_' + item.field_id,
            name: 'mods[]',
            height: 'auto',
            data: mods,
            values: item.mods.length > 0 ? item.mods.split(',') : [],
            on: function(obj) {
                if (obj.isAdd) {
                    options[item.field_id].values.push(obj.change[0].value);
                } else {
                    options[item.field_id].values.splice(options[item.field_id].values.indexOf(obj.change[0].value));
                }
            },
        };
    }
    $.get(window.location.href, {}, function(res) {
        $('#add').click(function() {
            makeItem();
            formRender();
        })

        function formRender() {
            $('button[data-op]').click(function() {
                var row = $(this.parentNode.parentNode.parentNode);
                if (this.dataset.op == 'up') {
                    var prev = row.prev();
                    if (prev.length == 0) return;
                    prev.before(row.prop("outerHTML"));
                    row.remove();
                    formRender();
                } else if (this.dataset.op == 'down') {
                    var next = row.next();
                    if (next.length == 0) return;
                    next.after(row.prop("outerHTML"));
                    row.remove();
                    formRender();
                } else if (this.dataset.op == 'set') {
                    var type = row.find('select[name^="type"]').val(),
                        value = row.find('input[name^="defaultvalue"]').val(),
                        field_id = row.find('input[name^="field_id"]').val(),
                        setting = row.find('input[name^="setting"]').val(),
                        btn = ['保存'],
                        formHtml,
                        yes,
                        area = ["400px"];
                    console.log(type, value);
                    if (type == 'switch') {
                        setting = setting.split(',');
                        formHtml = '<blockquote class="layui-elem-quote">启用状态指的是开关开启，关闭状态指的是开关关闭，文本选填，对应的值分别为1和0</blockquote><div class="layui-form-item"><label class="layui-form-label">默认状态</label><div class="layui-input-block"><input type="checkbox" name="defaultvalue" lay-skin="switch"' + (value == 1 ? ' checked=""' : '') + '></div></div>';
                        formHtml += '<div class="layui-form-item"><label class="layui-form-label">启用状态</label><div class="layui-input-block"><input type="text" class="layui-input" placeholder="启用状态显示的文本" maxlength="4" name="available" value="' + setting[0] + '"></div></div>';
                        formHtml += '<div class="layui-form-item"><label class="layui-form-label">关闭状态</label><div class="layui-input-block"><input type="text" class="layui-input" placeholder="关闭状态显示的文本" maxlength="4" name="unavailable" value="' + (setting[1] ? setting[1] : '') + '"></div></div>';
                        yes = function(index) {
                            formval = form.val('layer-form');
                            row.find('input[name^="setting"]').val(formval.available + ',' + formval.unavailable);
                            row.find('input[name^="defaultvalue"]').val(formval.defaultvalue == 'on' ? 1 : 0);
                            $('#defaultvalue_' + field_id).html(formval.defaultvalue == 'on' ? 1 : 0);
                            layer.close(index);
                        }
                    } else if (type == 'radio' || type == 'select') {
                        setting = setting.length > 0 ? setting.split(',') : [];
                        btn.push('新增');
                        area[0] = "600px";
                        formHtml = '<blockquote class="layui-elem-quote">若文本为空，则值=文本</blockquote><table class="layui-table"><colgroup><col width="80"><col width="200"><col width="200"><col width="60"></colgroup><thead><tr><th></th><th>值</th><th>文本</th><th>默认</th></tr></thead><tbody id="layertable">';

                        function makeRow(val = '', text = '') {
                            var code = '<tr><td><button type="button" class="layui-btn" data-tb="delete">删除</button></td>';
                            code += '<td><input type="text" class="layui-input" name="value[]" required="" lay-verify="required" value="' + (val ? val : '') + '"></td>';
                            code += '<td><input type="text" class="layui-input" name="text[]" value="' + (text ? text : '') + '"></td><td><input type="radio" name="default" value="1"' + (val.length > 0 && value == val ? ' checked=""' : '') + '></td></tr>';
                            return code;
                        }
                        setting.forEach(function(n) {
                            var values = n.split('|');
                            formHtml += makeRow(values[0], values[1]);
                        })
                        formHtml += '</tbody></table>';
                        yes = function(index) {
                            var formval = form.val('layer-form');
                            var radios = $('#layertable').find('input[type="radio"]');
                            var defaultvalue = -1;
                            for (var i = 0; i < radios.length; i++) {
                                if (radios[i].checked == true) {
                                    defaultvalue = i;
                                    break;
                                }
                            }
                            row.find('input[name^="defaultvalue"]').val(defaultvalue >= 0 ? formval['value[' + defaultvalue + ']'] : '');
                            $('#defaultvalue_' + field_id).html(defaultvalue >= 0 ? formval['value[' + defaultvalue + ']'] : '');
                            var settings = [];
                            var values = $('input[name^="value"]'),
                                texts = $('input[name^="text"]');
                            values.each(function(ind) {
                                settings.push(this.value + '|' + texts[ind].value)
                            })
                            row.find('input[name^="setting"]').val(settings.join(','));
                            layer.close(index);
                        }
                    } else if (type == 'checkbox' || type == 'multiselect') {
                        setting = setting.length > 0 ? setting.split(',') : [];
                        value = value.length > 0 ? value.split(',') : [];
                        btn.push('新增');
                        area[0] = "600px";
                        formHtml = '<blockquote class="layui-elem-quote">若文本为空，则值=文本</blockquote><table class="layui-table"><colgroup><col width="80"><col width="200"><col width="200"><col width="60"></colgroup><thead><tr><th></th><th>值</th><th>文本</th><th>默认</th></tr></thead><tbody id="layertable">';

                        function makeRow(val = '', text = '') {
                            console.log(value,val);
                            var code = '<tr><td><button type="button" class="layui-btn" data-tb="delete">删除</button></td>';
                            code += '<td><input type="text" class="layui-input" name="value[]" required="" lay-verify="required" value="' + (val ? val : '') + '"></td>';
                            code += '<td><input type="text" class="layui-input" name="text[]" value="' + (text ? text : '') + '"></td><td><input type="checkbox" name="default" value="1"' + (value.indexOf(val.toString()) >= 0 && val.length>0 ? ' checked=""' : '') + ' lay-skin="primary"></td></tr>';
                            return code;
                        }
                        setting.forEach(function(n) {
                            var values = n.split('|');
                            formHtml += makeRow(values[0], values[1]);
                        })
                        formHtml += '</tbody></table>';
                        yes = function(index) {
                            var formval = form.val('layer-form');
                            var checkboxes = $('#layertable').find('input[type="checkbox"]');
                            var defaultvalue = [],settings = [];
                            var values = $('input[name^="value"]'),
                                texts = $('input[name^="text"]');
                            values.each(function(ind) {
                                settings.push(this.value + '|' + texts[ind].value)
                            })
                            row.find('input[name^="setting"]').val(settings.join(','));
                            for (var i = 0; i < checkboxes.length; i++) {
                                if (checkboxes[i].checked == true) {
                                    defaultvalue.push(values[i].value);
                                }
                            }
                            row.find('input[name^="defaultvalue"]').val(defaultvalue.length > 0 ? defaultvalue.join(',') : '');
                            $('#defaultvalue_' + field_id).html(defaultvalue.length > 0 ? defaultvalue.join(',') : '');
                            layer.close(index);
                        }
                    } else {
                        formHtml = '<div class="layui-form-item"><label class="layui-form-label">默认文本</label><div class="layui-input-block"><input type="text" class="layui-input" placeholder="请不要输入特殊字符" name="defaultvalue" value="' + setting + '"></div></div>';
                        yes = function(index) {
                            var formval = form.val('layer-form');
                            row.find('input[name^="defaultvalue"]').val(formval.defaultvalue);
                            $('#defaultvalue_' + field_id).html(formval.defaultvalue);
                            layer.close(index);
                        }
                    }
                    layer.open({
                        area,
                        title: '设置',
                        content: '<form class="layui-form" lay-filter="layer-form" method="post" onsubmit="return false;">' + formHtml + '</form>',
                        btn: btn,
                        success: function() {
                            form.render();
                            $('button[data-tb="delete"]').click(function() {
                                $(this.parentNode.parentNode).remove();
                            })
                        },
                        yes: yes,
                        btn2: function() {
                            $('#layertable').append(makeRow());
                            form.render();
                            return false;
                        }
                    });
                } else if(this.dataset.op=='delete'){
                    $(this.parentNode.parentNode).remove();
                }
            })
            form.render();
            for (var x in options) {
                selects[x] = xmSelect.render(options[x])
                selects[x].setValue(options[x].values);
            }
        }

        function doReturn(res) {
            mods = res.data.infomod.split('\n').map(function(n,index) {
                return { name: n, value: index }
            });
            for (var i = 0; i < res.data.fields.length; i++) {
                makeItem(res.data.fields[i]);
            }
            formRender();
        }
        doReturn(res);
        form.on('submit(save)', function(data) {
            var loadingIndex = zadmin.loading();
            console.log(data.field);
            $.post(window.location.href, data.field, function(res) {
                layer.close(loadingIndex);
                zadmin.showReturn(res, function(res) {
                    $('#datalist').empty();
                    doReturn(res);
                    formRender();
                })
            })
            return false;
        })
        layer.close(loading);
    })

    exports('field', {})
})